package com.itheima.cs.help;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import com.itheima.cs.BuildConfig;

public class DbOpenHelper {
    private static final String CLS = "net.sourceforge.jtds.jdbc.Driver";
    private static final String BASE_URL = BuildConfig.DB_URL;
    private static final String PARAMS = BuildConfig.DB_PARAMS;
    private static final String USER = BuildConfig.DB_USER;
    private static final String PWD = BuildConfig.DB_PWD;

    private static final String URL = BASE_URL + ";" + PARAMS;

    public static Connection conn;
    public static Statement stmt;
    public static PreparedStatement pStmt;
    public static ResultSet rs;

    public static Connection getConnection() {
        try {
            Class.forName(CLS);
            // 使用安全拼接的URL
            conn = DriverManager.getConnection(URL, USER, PWD);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return conn;
    }


    public static void closeAll(){
        try{
            if(rs!=null){
                rs.close();
                rs=null;
            }
            if(stmt!=null){
                stmt.close();
                stmt=null;
            }
            if(pStmt!=null){
                pStmt.close();
                pStmt=null;
            }
            if(conn!=null){
                conn.close();
                conn=null;
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

    public static void closeAll(Connection conn) {
        try{
            if(rs!=null){
                rs.close();
                rs=null;
            }
            if(stmt!=null){
                stmt.close();
                stmt=null;
            }
            if(pStmt!=null){
                pStmt.close();
                pStmt=null;
            }
            if(conn!=null){
                conn.close();
                conn=null;
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}
